package com.yzhl.batch_sync.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author wangzu
 * @date 2018/10/12
 */
@Configuration
@MapperScan(basePackages = AliyunDataSourceConfig.PACKAGE, sqlSessionFactoryRef = AliyunDataSourceConfig.SQL_SESSION_FACTORY_NAME)
public class AliyunDataSourceConfig {

    static final String PACKAGE = "com.yzhl.batch_sync.mapper.aliyun";
    static final String MAPPER_LOCATION = "classpath:mapper/aliyun/*.xml";
    static final String DATA_SOURCE_NAME = "aliyunDataSource";
    static final String SQL_SESSION_FACTORY_NAME = "aliyunSqlSessionFactory";
    static final String TEMPLATE_NAME = "aliyunSqlSessionTemplate";

    @Bean(name = AliyunDataSourceConfig.DATA_SOURCE_NAME)
    @ConfigurationProperties(prefix = "spring.datasource.aliyun")
    public DataSource aliyunDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = AliyunDataSourceConfig.SQL_SESSION_FACTORY_NAME)
    public SqlSessionFactory aliyunSqlSessionFactory(@Qualifier(AliyunDataSourceConfig.DATA_SOURCE_NAME) DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(AliyunDataSourceConfig.MAPPER_LOCATION));
        return bean.getObject();
    }

    @Bean()
    public DataSourceTransactionManager aliyunTransactionManager(@Qualifier(AliyunDataSourceConfig.DATA_SOURCE_NAME) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

//    @Bean(name = AliyunDataSourceConfig.TEMPLATE_NAME)
//    public SqlSessionTemplate aliyunSqlSessionTemplate(@Qualifier(AliyunDataSourceConfig.SQL_SESSION_FACTORY_NAME) SqlSessionFactory sqlSessionFactory) {
//        return new SqlSessionTemplate(sqlSessionFactory);
//    }
}
